package com.songcha.library_common.ui.view.loading

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.songcha.library_common.util.dp2px
import com.songcha.library_common.util.sp2px
import com.songcha.library_common.R


class WaveLoadingView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0,
    defRes: Int = 0
) : View(context, attrs, defStyle, defRes) {

    companion object{
        private val ANIMATION_DURATION=2000L
        private val WAVE_COUNT=5
    }

    private var mValue=0f
    private var mAnimator:ValueAnimator?=null
    private var mPaint=Paint()
    private var mPath=Path()
    private var mProgress=0
    private var mProgressTextPaint=Paint()
    //private var mXferPaint=Paint()
    private var mColor=Color.parseColor("#6495ed")

    init {
        initView(context,attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?) {
        if (attrs != null) {
            val ta = context.obtainStyledAttributes(attrs, R.styleable.WaveLoadingView)
            mColor=ta.getColor(R.styleable.WaveLoadingView_wave_color,Color.parseColor("#6495ed"))
            ta.recycle()
        }


        mPaint.color=mColor
        mPaint.isAntiAlias=true

        //mXferPaint.isAntiAlias=true

        mProgressTextPaint.color=Color.WHITE
        mProgressTextPaint.textSize=20f.sp2px()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val widthMode=MeasureSpec.getMode(widthMeasureSpec)
        val heightMode=MeasureSpec.getMode(widthMeasureSpec)

        if(widthMode!=MeasureSpec.EXACTLY || heightMode!=MeasureSpec.EXACTLY){
            setMeasuredDimension(200.dp2px(),200.dp2px())
        }else
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    fun setProgress(progress:Int){
        if(progress>100) mProgress=100
        if(progress<0) mProgress=0
        if(mProgress!=progress){
            mProgress=progress
            invalidate()
        }
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if(canvas==null){
            return
        }

        if(mProgress==0) {
            return
        }

        //val saveCount = canvas.saveLayer(0f,0f,width.toFloat(),height.toFloat(),mXferPaint)

     /*   val childRect=Rect(0,0,child.width,child.height)
        val childBitmap=BitmapUtil.view2Bitmap(getChildAt(0),childRect,1f)
        canvas.drawBitmap(childBitmap!!,0f,0f,mXferPaint)
        mXferPaint.xfermode=PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
        canvas.drawBitmap(createWave(),0f,0f,mXferPaint)
        mXferPaint.xfermode=null*/


        //canvas.restoreToCount(saveCount)

        //canvas.drawBitmap(createWave(),0f,0f,mXferPaint)

        createWave(canvas)

    }

    fun createWave(canvas:Canvas){
        //val bitmap = Bitmap.createBitmap(1000, 1000, Bitmap.Config.ARGB_8888)
        //val canvas = Canvas(bitmap)

         val valleyHeight=height/6
         val offset=(WAVE_COUNT-2)*width/2*mValue

         mPath.reset()

         val waveHeight=(height*(100-mProgress)*1.0/100).toFloat()

         mPath.moveTo(0f-offset,waveHeight)

         for(i in 0 until WAVE_COUNT){
             var controlY=0f
             val waveHeightDelta=(valleyHeight*2*mValue)
             if(i%2==0){
                 controlY=(waveHeight-valleyHeight+waveHeightDelta)
             }else{
                 controlY=(waveHeight+valleyHeight-waveHeightDelta)
             }
             var controlX=(width/4+(width/2*i)-offset).toFloat()
             val endX=(width/2+(width/2*i)-offset).toFloat()
             val endY=waveHeight

             mPath.quadTo(controlX,controlY,endX,endY)
         }

         mPath.lineTo(width.toFloat(),height.toFloat())
         mPath.lineTo(0f,height.toFloat())
         mPath.close()

         canvas.drawPath(mPath,mPaint)

        //return bitmap

        /*if(mProgress>0){
            val str="$mProgress%"
            val textRect= FontUtil.getTextBounds(str,mProgressTextPaint.textSize,false)?:return
            val fontMetrics= FontUtil.getFontMetrics(mProgressTextPaint.textSize,false)?:return
            val textHeight=(fontMetrics.top.absoluteValue+fontMetrics.bottom)

            canvas.drawText(str,(width/2-textRect.width()/2).toFloat(),(height-textHeight)/2+fontMetrics.top.absoluteValue,mProgressTextPaint)

        }*/
    }

    fun startAnimation(){
        mAnimator=ValueAnimator.ofFloat(0f,1f)
        mAnimator?.apply {
            repeatCount=-1
            //repeatMode=ValueAnimator.REVERSE
            interpolator=LinearInterpolator()
            addUpdateListener {
                mValue=it.animatedValue as Float
                invalidate()
            }
            duration=ANIMATION_DURATION
            start()
        }

    }


    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        startAnimation()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mAnimator?.cancel()
    }


}